package com.atguigu.bigdata.spark.core.wc

import org.apache.spark.rdd.RDD
import org.apache.spark.{SparkConf, SparkContext}

/**
  * create by undeRdoG on  2021-06-06  14:54
  * 凡心所向，素履以往，生如逆旅，一苇以航。
  */
object Spark03_WordCount {

  def main(args: Array[String]): Unit = {

    val sparkConf = new SparkConf().setMaster("local").setAppName("WordCount")
    val sc = new SparkContext(sparkConf)


    val lines: RDD[String] = sc.textFile("datas")

    val words: RDD[String] = lines.flatMap(_.split(" "))

    val wordToOne: RDD[(String, Int)] = words.map(
      word => {
        (word, 1)
      }
    )


    /**
      * spark 中的方法，reduceByKey
      * 对相同key的数据，可以对value进行reduce操作
      **/
    val wordTocount = wordToOne.reduceByKey((x, y) => {
      x + y
    })


    /**
      * 简化原则：只出现一次的参数， _ 替代即可
      **/
    val wordToCount1 = wordToOne.reduceByKey(_ + _)

    wordToCount1.collect().foreach(println)

    val array: Array[(String, Int)] = wordTocount.collect()


    array.foreach(println)
    sc.stop()
  }
}
